﻿//for order.html
var loginStatus = getL();

var orderValidateWindow;
$(document).ready(function(){
	$("#loginBtn").click(function() {
		user_login2();

	});
	if ('1' == getCT()) {
		document.location.href = "/" + i18n.name + "/index.html";
	}
	getNoneCrabsProList();
	$("#order-submit").removeAttr("disabled");
	$('input:checkbox').attr("checked",false);
	$('input:radio').attr("checked",false);
	//$('input:checkbox[name=print]').attr("checked",true);
	$("#r_modify").val('');
	$("#4print").attr("checked","checked");
	$('input:radio[name=4print]').attr("checked",true);
 
	if (getL() == '2' &&  (getCT() == '0' || getCT() == '2') && getUT() == '0') {// 已登录个人会员
		var userMobile = '';
		var isUserMobileValidate= '';

		asyncCallService('/service/member/memberIndexInfo', 'get', 'json', '', function(data) {
			if(data != null){
				isUserMobileValidate = data.mobileIsValidate;
				userMobile = data.mobile;
			}
		});

		$('#s_mobile').blur(function() {
			var mobile = $(this).val();
			if (getL() == '2' && isMobel(mobile) && isUserMobileValidate == 'Y' && 
					userMobile != mobile) {
				// 已登录会员如果填写的手机号不是会员手机号则提示
				$('#send_Validform_checktip').html('小主儿，填写会员手机号方可享受相关权益噢！');
			}
		});
		
		if(getRegionCode()=='cn'){ // 大陆地区
			syncCallService('/service/user/policy/actConfig?scodes=send_full_give_token,mem_first_succe_send', 'get', 'json', '', function(data) {
				if(data && data.send_count){
					$('.send_count').text(data.send_count);
					$('.mem_coupon_amt').text(data.mem_coupon_amt);
					$('#module_order_div').show();
				}
			});
		}
	}
	
   var orderform = $("#orderform").Validform({
       usePlugin:{
            passwordstrength:{minLen:6,maxLen:30}
        },
        tiptype:function(msg,o,cssctl){
            if(!o.obj.is("form")){
                var objtip=o.obj.parents().children(".Validform_checktip");
                cssctl(objtip,o.type);
                objtip.removeClass("Validform_right");
                objtip.text(msg);
            }
        },
        datatype:{
        },
        ajaxPost:true,
        callback:function(data){
        	if(data.status == "success"){
        		$("#order-submit").attr("disabled",true);
        		if(loginStatus != '2'){//下单后改变登录状态
        			/*var l = loginStatus=='3'?'1':'2';
        			addCookieWithNoExpires("l", l);*/
        			var addrs = getAddressData();
        			var cookieAddrs = getCookie('UserAddrs');
        			if(cookieAddrs != undefined && cookieAddrs != null && cookieAddrs != ''){
        				addrs += cookieAddrs;
        			}
        			addCookie('UserAddrs',addrs);
        		}
          	  var waybilltype = data.waybillType;
          	  if(waybilltype != undefined && waybilltype == "4"){
          	      window.location.href="/"+i18n.name + "/order/" + "order_success.html?type=all&ot=4&id="+data.orderNo + "&wt=A4";
          	  }else if(waybilltype == "H4"){
          		  window.location.href="/"+i18n.name +"/order/" +  "order_success.html?type=all&ot=4&id="+data.orderNo + "&wt=H4";
          	  }else if(waybilltype == "ZNZD"){
          		  window.location.href="/"+i18n.name +"/order/"  + "order_success.html?type=all&ot=4&id="+data.orderNo + "&wt=ZNZD";
          	  }else {
                  window.location.href="/"+i18n.name +"/order/"  + "order_success.html?type=all&ot=4&id="+data.orderNo + "&wt=C";
              }
        	}else{
        		
        		if(data == 'errorKeyword'){
        			handleBlackKeyword();
        			return;
        		}else{
	        		if(data.status == "nologin"){
	        			sfAlert(i18n.order_address_error);
	        		}else if(data.status == "reservetm_error"){
	        			sfAlert(i18n.order_address_reservetm_error);
	        		}else if(data.status == "crab_none_pri_pro"){
	        			sfAlert(i18n.none_crabs_pri_province_batch);
	        		}else if(data.status == "crab_none_recpay"){
	        			sfAlert(i18n.crabs_none_rec_pay);
	        		}else if(data.status == "spite_order"){
	        			$("#orderValidateTip").html("您好，您已使用手机号码"
	        				+$("#s_mobile").val()
	        				+"累计下单5次，如需继续下单，请获取手机验证码或登陆会员。");
	        			orderValidateWindow=art.dialog({
	        				title : i18n.MYSF,
	        				height:100,
	        				lock:true,
	        				content : document.getElementById('orderValidate')
	        			});
	        		}else if(data.status == "account_err"){//代码回退
	        			sfAlert("无效的月结账号");
	        		}else if(data.status == "account_empty"){
	        			sfAlert("寄付月结时，月结卡号必填");
	        		}else{
	        			sfAlert(i18n.order_commit_error);
	        		}
	        		$("#order-submit").removeAttr("disabled");
        		}
        	}
        }
    });
   $('#payway').change(function(){
		/*var selVal=$('#payType').val();
		if(selVal=='1' || selVal=='2'){
			//非寄付月结
			$('.selectout1').hide();
		}
		if(selVal=='3'){
			//寄付月结
			$('.selectout1').show();
		}	*/
	});
   var sendForm = $("#sendForm").Validform({
        tiptype:function(msg,o,cssctl){
            if(!o.obj.is("form")){
                var objtip=$("#send_Validform_checktip");
                cssctl(objtip,o.type);
                objtip.removeClass("Validform_right");
                objtip.text(msg);
            }
        },
        datatype:{
            "smobile":function(gets,obj,curform,regxp){
            	
            	var reg1=/^\d{7,8}$/,
				reg2=regxp["m"],
				phone=$("#s_phone").val();
				if(phone != ''){
					if(reg1.test(phone)){
						if(gets != ''){
							return reg2.test(gets);
						}
						return true;
					}
				}
				
				if(reg2.test(gets)){
					
					return true;
				}
				return false;  	
			},
			"sprovinceName":function(gets,obj,curform,regxp){
			    var tipValue = obj.attr("tip");
	        	if(gets =='' || gets==tipValue){
	    			return false;
	    		}
	        	var sprovinceId = $("#s_provinceId").val();
	        	if(sprovinceId =='' || sprovinceId == undefined){
	    			return false;
	    		}
	        	return true;
	        },
	        "scityName":function(gets,obj,curform,regxp){
	            var tipValue = obj.attr("tip");
	        	if(gets =='' || gets==tipValue){
	    			return false;
	    		}
	        	var scityId = $("#s_cityId").val();
	        	if(scityId =='' || scityId == undefined){
	    			return false;
	    		}
	        	return true;
	        },
	        "stel":function(gets,obj,curform,regxp){
				var reg1=/^\d{7,8}$/;
				if($.trim(gets) != ''){
					$('#pwrong').removeClass("Validform_wrong");
					if(reg1.test(gets)){
						return true;
					}
					return false;
				}
				return true;
			},
			"areacode":function(gets,obj,curform,regxp){
				var reg=/^\d{3,4}$/;
				if(gets != ''){
					if(!reg.test(gets)){
						return false;
					}
				}
				return true;
			},
			"ssext":function(gets,obj,curform,regxp){
				var reg=/^\d{1,5}$/;
				if(gets != ''){
					if(!reg.test(gets)){
						return false;
					}
				}
				return true;
				
			},
			"weight":function(gets,obj,curform,regxp){
				var reg=/^\d{1,3}$/;
				if($.trim(gets) == ''){
					return false;
				}else{
					if(!reg.test(gets) || gets >100 || gets <= 0){
						return false;
					}
				}
				return true;
				
			}
        },
        ajaxPost:true,
        callback:function(id){
        	if(id == 'errorKeyword'){
        		handleBlackKeyword();
        		return;
        	}else if(id != null){
        		$("#s_id").val(id);
        		 addToSendAddr();
        	}
        }
    });
   var recForm = $("#recForm").Validform({       
        tiptype:function(msg,o,cssctl){
            if(!o.obj.is("form")){
                //var objtip=o.obj.parents().children(".Validform_checktip");
                var objtip=$("#rec_Validform_checktip");
                cssctl(objtip,o.type);
                objtip.text(msg);
            }
        },
        ajaxPost:true,
        callback:function(id){
        }
    });
    //保存寄件人地址
   $("#saveSend").click(function(){
	   var s_fullname = $("#s_fullname").val();
	   if($.trim(s_fullname) == ''){
		   $("#s_fullname").val('');
		   $("#send_Validform_checktip").text(i18n.order_sender_invalid).addClass("Validform_wrong");
		   return false;
	   }
	   
	   var reg = /^\d{7,8}$/;
	   var s_phone = $("#s_phone").val();
	   if(s_phone != ''){
		   if(!reg.test(s_phone)){
			   $("#send_Validform_checktip").text(i18n.order_telephone_invalid);
			   $("#send_Validform_checktip").addClass("Validform_wrong");
      			return false;
      		}
	   }
	   var reg2 = /^\d+$/;
	   var s_extnumber = $("#s_extnumber").val();
	   var s_qh = $("#s_qh").val();
	   if(s_extnumber != ''){
		   if(!reg2.test(s_extnumber)){
			   $("#send_Validform_checktip").text(i18n.order_areacode_invalid);
			   $("#send_Validform_checktip").addClass("Validform_wrong");
      		   return false;
      		}
	   }
	   if(s_qh != ''){
		   if(!reg2.test(s_qh)){
			   $("#send_Validform_checktip").text(i18n.order_areacode_invalid);
			   $("#send_Validform_checktip").addClass("Validform_wrong");
      		   return false;
      		}
	   }
	   
	   var reg3 = /^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$/;
	   var s_mobile = $("#s_mobile").val();
	   if(s_mobile != ''){
		   if(!reg3.test(s_mobile)){
			   $("#send_Validform_checktip").text(i18n.enter_right_mobile_num).addClass("Validform_wrong");
			   return false;
      		}
	   }
	   
	   if (s_mobile == '' && s_phone == '') {
		   $("#send_Validform_checktip").text(i18n.order_phone_or_telephone).addClass("Validform_wrong");
		   return false;
	   }
	   
	   var sprovinceName = $("#s_provinceName").val();
	   if(sprovinceName == '' || sprovinceName == i18n.order_province){
		   $("#send_Validform_checktip").text(i18n.order_province_invalid).addClass("Validform_wrong");
		   return false;
	   }
		   
	   var scityName = $("#s_cityName").val();
	   if(scityName == '' || scityName == i18n.order_city){
		   $("#send_Validform_checktip").text(i18n.order_city_invalid).addClass("Validform_wrong");
		   return false;
	   }
	   
	   var s_address = $("#s_address").val();
	   if($.trim(s_address) == '' || s_address == i18n.myorder_detail_address || s_address == i18n.myorder_detail_address_1){
		   $("#send_Validform_checktip").text(i18n.order_address_empty).addClass("Validform_wrong");
		   return false;
	   }
	   
	   //判断是否是嘿客寄件
	   if(!checkSendVirtualAddress()){
		   $("#send_Validform_checktip").text(i18n.order_address_accept_all).addClass("Validform_wrong");
		   return false;   
	   }
	   if(loginStatus == '2' ){
		   $("#sendForm").attr("action","/service/addrbook/address/save/orderaddr");
			sendForm.ajaxPost(false,true);
			 addToSendAddr();
			return true;
	   }else{
		   var flag =  sendForm.check(false);
		   if(flag){
			   addToSendAddr();
		   	}
	   }
	  
	});
   //保存收件人地址
   $("#saveRec").click(function(){
	   if($("#recContextAddr").is(":visible")){
		   if(loginStatus == '2' ){
			   $("#recForm").attr("action","/service/addrbook/address/save/orderaddr");
				recForm.ajaxPost();
				return true;
		   }
	   }
	});
   
    //提交订单
    $("#order-submit").click(function(){
    	try{
    		showTip();
    		orderSubmit(orderform);
    	}finally{
    		closeTip();
    	}
    });

	   if(loginStatus == '2' ){
		    //您本月收寄件天数已达n天，达到5天可以奖励100积分哦
		    //您本月收寄件天数已达n天，每增加5天都可以奖励100积分哦
		    var statisticsMsg="";
		    syncCallService('/service/order/statistics', 'post', 'JSON', '', function(data){        
		        if(data < 5&& data>= 0){
		        	statisticsMsg="天，达到5天可以奖励100积分哦";
		        }else if(5<=data && data< 30){
		        	statisticsMsg="天，每增加5天都可以奖励100积分哦";
		        }else{
		        	return;
		        }
		        $("<span id='perfix' style='color:#515151;'/>").insertAfter($('#saveSend')).text("您本月收寄件天数已达");
		        $("<span id='sCount' style='color:#990000;'/>").insertAfter($('#perfix')).text(data);
		        $("<span id='suffix' style='color:#515151;'/>").insertAfter($('#sCount')).text(statisticsMsg);
			}, function(){
			});
	   }
});

function orderSubmit(orderform){

    if(undefined==$("#confirm_read:checked").val()){
		sfAlert('请阅读运单背书条款');
		return;		    	
    }
	///////寄件人自动提交////////
	$("#saveSend").click();
	////////收件人自动提交/////////
	var recform = $("#recs").find("form a[but='sub']");
	recform.click();  //未保存的自动保存
	var s = $("#sendContextAddr").is(":visible");
	/*if(s){
		return false;
	}*/
	var f = $("#recs").find("form");
	var v = f.is(":visible");
	if(v){
		return false;
	}
	///////////the end//////////
	
   var formJson = getFormJson();
   
   if(formJson == i18n.none_crabs_pri_province_batch){
	   sfAlert(i18n.none_crabs_pri_province_batch);
	   return false;
   }
   if(formJson == i18n.crabs_none_rec_pay){
	   sfAlert(i18n.crabs_none_rec_pay);
	   return false;
   }
   
   if(formJson == i18n.order_sender_empty){
	   sfAlert(i18n.order_sender_empty);
	   return false;
   }
   if(formJson == i18n.order_recipient_empty){
	   sfAlert(i18n.order_recipient_empty);
	   return false;
   }
   if(formJson == i18n.order_recipient_over_ten){
	   sfAlert(i18n.order_recipient_over_ten);
	   return false;
   }
   
   var print=$("#print").attr("checked");  //A4和大陆的需判断寄收人重复
   if(print == 'checked' && $("#nation").val()==i18n.order_nation_Inland){
	   ///////寄件人和收件人不能重复//////
		var send_fullname = $("#send_fullname").text();
		var send_address = $("#send_address").text();
		
		$('input:checkbox[name="useRecAddr"]').not("input:checked").each(function(x){ //重复的收件地址不能添加
    		var selectRecAddr = $("#selectRecAddr"+$(this).val());
    		var fullnames = selectRecAddr.find("#fullnames").text();
    		var addresss = selectRecAddr.find("#addresss").text();
    		if(fullnames==send_fullname && send_address == addresss ){
				  sfAlert(i18n.order_sender_recipient_same);
				  return false;
			  }
		});
    }
	var printVal = $('input:radio[name="print"]:checked').val(); //$("#printDiv :checked").val();
    var reserveTime = $('input:checkbox[name="reserveTime"]:checked').val();
    if(reserveTime == undefined&&"H4"!=printVal){
       if(currentIsOrder()==false){  //当前下单时间不在服务时间
    	   sfAlert(i18n.order_over_reserve_time);
		   //$("#reserveTime:hidden").parent().parent().show().find(":checked").parent().parent().next("#yuyue:hidden").show();
			return false; 
		}
    }else{
    	if("H4"!=printVal){
    		var cd = new Date().format('yyyy-MM-dd hh:mm');
    		var bookingDate = $("#ydate").val();
    		var bookingHour = parseInt($("#yhour").val());
    		var bookingMinute = $("#yminu").val();
    		var bookingTm = bookingDate + " " + 
    		(bookingHour.length==1?("0"+bookingHour):bookingHour) + ":" + 
    		(bookingMinute==null?"00":bookingMinute) ;
    		if(bookingDate =='' || bookingHour===''||bookingMinute==''){
    			sfAlert(i18n.order_make_booking);
    			return false; 
    		}
    		if(bookingTm<cd){
    			sfAlert(i18n.order_booking_time_wrong);
    			return false;
    		}
    	}
    }
    if(loginStatus != '2'){
    	var mobile = $("#s_mobile").val();
    	if (mobile !='' && isIllegalOrder(mobile,'MOBILE')){//验证未登录用户是否恶意下单
			sfAlert('您下单过于频繁，请登录或注册后再下单，能享受更多的优惠');
			return;
		}
    	
    	var phone = $("#send_phone").text();
    	if(phone.lastIndexOf(',') != -1){
    		phone = phone.substring(0,phone.lastIndexOf(','));
        }
    	if(phone != '' && isIllegalOrder(phone,'PHONE')){
    		sfAlert('您下单过于频繁，请登录或注册后再下单，能享受更多的优惠');
			return;
    	}
    }
    
   $("#orderJSON").attr("value",formJson);
   $("#loginStatus").attr("value",loginStatus);
   orderform.ajaxPost();
   return true;
  
}

//验证未登录用户是否恶意下单
function isIllegalOrder(key,type){
	var param = {'key':key,'type':type};
	var returnStr = false;
	syncCallService('/service/order/isIllegalOrder', 'post', 'JSON', param, function(data){
			returnStr = data;
		}, function(){
		});
	return returnStr;
}

var tosendaddr,torecaddr;
//确定选择发件人地址填充到发件人
function entrySendAddr(){
	var sendAddrId=$('input:radio[name="selectSendAddress"]:checked').val();
	if(sendAddrId == undefined){
		sfAlert(i18n.order_sender_address_select);
		return;
	}
	 $.ajax({
		url : '/service/addrbook/address/'+sendAddrId,
		type : 'get',
		data : '',
		contentType: "application/x-www-form-urlencoded; charset=utf-8", 
		dataType : 'JSON',
		success : function(item) {
			$("#s_id").val(item.userAddressId);
			$("#s_company").val(item.company==null?'':item.company);
			$("#s_fullname").val(item.fullname==null?'':item.fullname);
			var phone = item.phone==null?'':item.phone;
			if(phone.indexOf('-', 0) != -1){
				if(phone.split("-").length == 2){
					phone = phone.split('-', 2);
					if(phone[0].length > 4){
						$("#s_phone").val(phone[0]);
						$("#s_extnumber").val(phone[1]);
					} else {
						$("#s_qh").val(phone[0]);
						$("#s_phone").val(phone[1]);
					}
				} else {
					phone = phone.split('-', 3);
					$("#s_qh").val(phone[0]);
					$("#s_phone").val(phone[1]);
					$("#s_extnumber").val(phone[2]);
				}
			}else{
				$("#s_phone").val(phone);
			}
			$("#s_mobile").val(item.mobile==null?'':item.mobile);
			$("#s_countyId").val(item.countyId==null?'':item.countyId);
			$("#s_cityId").val(item.cityId==null?'':item.cityId);
			$("#s_provinceId").val(item.provinceId==null?'':item.provinceId);
			$("#s_countyName").val(item.countyName==null?'':item.countyName);
			$("#s_cityName").val(item.cityName==null?'':item.cityName);
			$("#s_provinceName").val(item.provinceName==null?'':item.provinceName);
			$("#s_address").val(item.address==null?'':item.address);
			
		}
	});
	 tosendaddr.close();
}


//确定选择收件人地址填充到收件人
function entryRecAddr(){
	var obj = $('input:radio[name="selectRecAddress"]:checked');
	if(obj.length<=0){
		sfAlert(i18n.order_recipient_address_select);
		return;
	}
	var recAddrId = $('input:radio[name="selectRecAddress"]:checked').val();
	$.ajax({
		url : '/service/addrbook/address/'+recAddrId,
		type : 'get',
		data : '',
		contentType: "application/x-www-form-urlencoded; charset=utf-8", 
		dataType : 'JSON',
		success : function(item) {
			  var id = $("#selectRecId").val();
			  fillRecDefAddr(item,id); 
		}
	});

   torecaddr.close();
   $("#rec_address_infoform #pageNo").val(1);
}


//从寄件人地址薄中选择
function toSendUserAddr(){
	$("#sendAddrUL tr").remove();
	 if(loginStatus == 1 || loginStatus == 3){
		 sfAlert(i18n.order_address_book_no_data);
		 return;
	 }else{
		 
		$.ajax({
			url : '/service/addrbook/address/orderaddr/send',
			type : 'get',
			data : '',
			contentType: "application/x-www-form-urlencoded; charset=utf-8", 
			dataType : 'JSON',
			success : function(data) {
				if(data != undefined){
					if(data.length<=0){
						sfAlert(i18n.order_address_book_no_data);
						return;
					}else{
						$.each(data,function (i,item){
							var style = '';
							if(i % 2 == 0){
								style = '<tr onMouseOver="javascript:trMouseover(this);" onMouseOut="javascript:trMouseout(this);" onClick="javascript:trOnClick(this);">';
							}else{
								style = '<tr onMouseOver="javascript:trMouseover(this);" onMouseOut="javascript:trMouseout(this);" onClick="javascript:trOnClick(this);" class="odd">';
							}
							var rows = style + '<td class="list-select"><input type="radio" name="selectSendAddress" value="'+item.userAddressId+'" />'+
							'<input type="hidden" id="sendid" name="sendid" value="'+item.userAddressId+'">'+
							'</td>' +
							'<td class="list-name">'+(item.fullname==null?'':item.fullname)+'</td>'+
							'<td class="list-contact">'+(item.mobile==null?'':item.mobile)+
							(item.phone==null?'':' / ' + item.phone)+ '</td>' +
							'<td class="list-address">'+item.provinceName+item.cityName+item.countyName+item.address+'</td>'+
							'</tr>';
							$("#sendAddrUL").append(rows);
							
						});
						tosendaddr = art.dialog({
				        	title : i18n.order_add_sender_info,
				        	background : 'none',
				        	padding : 15,
				        	width:900,
				        	content : document.getElementById('send_address_info')
				        });
					}
				}
			}
		});
	 }
}

//从收件人地址薄中选择
function getRecAddr(id,condition){
	
	if(id != ''){
		$("#reclike").val('');
	}
	$("#recAddrUL tr").remove();
	
	var params = '';
	if(condition != '' && condition != undefined){
		params = condition;
	}
	 if(loginStatus == 1 || loginStatus == 3){
		 sfAlert(i18n.order_address_book_no_data);
		 return;
	 }else{
		 $.ajax({
			url : '/service/addrbook/address/page/R?condition='+params+'&sort=',
			type : 'get',
			data : $("#rec_address_infoform").serialize(),
			contentType: "application/x-www-form-urlencoded; charset=utf-8", 
			dataType : 'JSON',
			success : function(data) {
				if(data == null){
					sfAlert(i18n.order_address_book_no_data);
					$("#rec_pagingBar").empty();
					return;
				}
				
				if(data.result != undefined){
					if(data == null || data.result.length<=0){
						sfAlert(i18n.order_address_book_no_data);
						return;
					}else{
						//var isUcmp = isUcmpSwitch(); 
						var rowsAll = '';
						$.each(data.result,function (i,item){
							var style = '';
							if(i % 2 == 0){
								style = '<tr onMouseOver="javascript:trMouseover(this);" onMouseOut="javascript:trMouseout(this);" onClick="javascript:trOnClick(this);">';
							}else{
								style = '<tr onMouseOver="javascript:trMouseover(this);" onMouseOut="javascript:trMouseout(this);" onClick="javascript:trOnClick(this);" class="odd">';
							}
							var address = "";
							//if(!isUcmp){
								address = item.provinceName+item.cityName+(item.countyName == null ? "":item.countyName)+item.address;
							//}else{
								//address = item.address;
							//}
							var rows = style + '<td class="list-select-long"><input type="radio" name="selectRecAddress" value="'+item.userAddressId+'" /> '+
							'<input type="hidden" id="recid" name="recid" value="'+item.userAddressId+'">'+			
							'</td>' +
							'<td class="list-name">' + (item.fullname==null?'':item.fullname)+'</td>' +
                            '<td class="list-contact">'+ (item.mobile==null?'':item.mobile)+
                            ((item.phone==null||item.phone=='')?'':' / ' + item.phone) +'</td>' +                            
                            '<td class="list-address">' + address+'</td>' +
                            '</tr>';	
							rowsAll += rows;
						});
						$("#recAddrUL").html(rowsAll);
						$("#rec_pagingBar").empty();
						$("#rec_pagingBar").append(data.pagingBar);
						if(id != undefined && id!=''){
							$("#selectRecId").val(id);
						}
						if(torecaddr != undefined){
							torecaddr.close();
						}
						 torecaddr = art.dialog({
					        	title : i18n.order_add_recipient_info,
					        	lock:true,
					        	background : '#444',
					        	padding: 15,
					        	width:900,
					        	content : document.getElementById('rec_address_info')
					        });
					}
				}
			}
		});
	 }
}

//从寄件人地址薄中选择

function openSenderBook(){
	$("#send_address_infoform #pageNo").val(1);
	$("#sendlike").val('');
	getSenderAddr('');
}

function getSenderAddr(condition){
	var params = '';
	if(condition != '' && condition != undefined){
		params = condition;
	}
	$("#sendAddrUL tr").remove();
	 if(loginStatus == 1 || loginStatus == 3){
		 sfAlert(i18n.order_address_book_no_data);
		 return;
	 }else{
		 $.ajax({
			url : '/service/addrbook/address/page/S?condition='+params+'&sort=',
			type : 'get',
			data : $("#send_address_infoform").serialize(),
			contentType: "application/x-www-form-urlencoded; charset=utf-8", 
			dataType : 'JSON',
			success : function(data) {
				
					if(data == null || data.result.length<=0){
						sfAlert(i18n.order_address_book_no_data);
						$("#send_pagingBar").empty();
						return;
					}else{
						//var isUcmp = isUcmpSwitch();
						var rowsAll = '';
						$.each(data.result,function (i,item){
							var style = '';
							if(i % 2 == 0){
								style = '<tr onMouseOver="javascript:trMouseover(this);" onMouseOut="javascript:trMouseout(this);" onClick="javascript:trOnClick(this);">';
							}else{
								style = '<tr onMouseOver="javascript:trMouseover(this);" onMouseOut="javascript:trMouseout(this);" onClick="javascript:trOnClick(this);" class="odd">';
							}
							
							//var itemStr = objToJsonStr(item);
							var address = "";
							//if(!isUcmp){
								address = item.provinceName+item.cityName+(item.countyName == null ? "":item.countyName)+item.address;
							//}else{
								//address = item.address;
							//}
							var rows = style + '<td class="list-select-long"><input type="radio" name="selectSendAddress" value="'+item.userAddressId+'" /> '+
							'<input type="hidden" id="recid" name="sendid" value="'+item.userAddressId+'">'+			
							'</td>' +
							'<td class="list-name">' + (item.fullname==null?'':item.fullname)+'</td>' +
                            '<td class="list-contact">'+ (item.mobile==null?'':item.mobile)+
                            ((item.phone==null||item.phone=='')?'':' / ' + item.phone) +'</td>' +                            
                            '<td class="list-address">' + address+'</td>' +
                            '</tr>';							
							rowsAll += rows;
						});
						$("#sendAddrUL").html(rowsAll);
						$("#send_pagingBar").empty();
						$("#send_pagingBar").append(data.pagingBar);
						if(tosendaddr != undefined){
							tosendaddr.close();
						}
						tosendaddr = art.dialog({
					        	title : i18n.order_add_sender_info,
					        	lock:true,
					        	background : '#444',
					        	padding: 15,
					        	width:900,
					        	content : document.getElementById('send_address_info')
					        });
					}
				}
			
		});
	 }
}

function chooseSender(){
	var checkedAddrId = $('input:radio[name="selectSendAddress"]:checked').val();
	
	if(checkedAddrId != undefined && checkedAddrId != null && checkedAddrId != ''){
		syncCallService('/service/addrbook/address/' + checkedAddrId, 'get', 'JSON', '', function(data){
			if(data!=null){
				$("#s_fullname").val("");
				$("#s_company").val("");
				$("#s_mobile").val("");
				$("#s_phone").val("");
				$("#s_extnumber").val("");
				$("#s_qh").val("");
				$("#s_provinceName").val("");
				$("#s_provinceId").val("");
				$("#s_cityName").val("");
				$("#s_cityId").val("");
				$("#s_countyName").val("");
				$("#s_countyId").val("");
				$("#s_address").val("");
				
				var item = data;
				$("#s_fullname").val(item.fullname);
				$("#s_company").val(item.company);
				$("#s_mobile").val(item.mobile);
				$("#s_id").val(item.userAddressId);
				var phone = (item.phone==null?'':item.phone);
				if(phone.indexOf('-', 0) != -1){
					if(phone.split("-").length == 2){
						phone = phone.split('-', 2);
						if(phone[0].length > 4){
							$("#s_phone").val(phone[0]);
							$("#s_extnumber").val(phone[1]);
						} else {
							$("#s_qh").val(phone[0]);
							$("#s_phone").val(phone[1]);
						}
					} else {
						phone = phone.split('-', 3);
						$("#s_qh").val(phone[0]);
						$("#s_phone").val(phone[1]);
						$("#s_extnumber").val(phone[2]);
					}
				}else{
					$("#s_phone").val(phone);
				}
				$("#s_provinceName").val(item.provinceName);
				$("#s_provinceId").val(item.provinceId);
				$("#s_cityName").val(item.cityName);
				$("#s_cityId").val(item.cityId);
				$("#s_countyName").val(item.countyName);
				$("#s_countyId").val(item.countyId);
				
				var isUcmp = isUcmpSwitch(); 
				var address = "";
				if(!isUcmp){
					address = item.address;
				}else{
					address = item.address.replace(item.provinceName+item.cityName+item.countyName,'');
				}
				$("#s_address").val(address);
				var addressFirm = new AddressFirm();
				addressFirm.ChangeFuncName=showZD;
				addressFirm.ChangeAreaFuncName=checkZNZDPrint;
				AddressHelper.loadCityAndAreaData('s_provinceId','s_provinceName','s_cityId','s_cityName','cityBoxBoxId','s_countyId','s_countyName','countyBoxId',addressFirm);
			}
		}, function(){
			
		});
		
	}
	tosendaddr.close();
}


//运单背书条款
var js_waybill_clause;
function open_waybill_clause(){
	
	var text = i18n.order_contract;
				
	$("#div_waybill_clause").html(text);
	
	js_waybill_clause = art.dialog({
     	title : '',
     	background : 'none',
     	padding: 15,
     	width:600,
     	content : document.getElementById('div_waybill_clause')
     });
}


//当前是否可以下单
function currentIsOrder(){
	if($("#znzdprint:checked").size()>0)return true;
	var cityId = $("#s_cityId").val();
	if(cityId == undefined || cityId == ''){
		cityId = 'default';
	}
	var flag ='';
	syncCallService('/service/order/order/compareTime/' + cityId, 'get', 'JSON', '', function(data){
		flag = data;
	}, function(){
		return false;
	});
	return flag.isOrder;
}

//当前是否可以下单
function currentIsOrderEasy(){
	if($("#znzdprint:checked").size()>0)return true;
	var cityId = $("#s_cityId").val();
	if(cityId == undefined || cityId == ''){
		cityId = 'default';
	}
	var flag ='';
	syncCallService('/service/order/order/compareTime/' + cityId, 'get', 'JSON', '', function(data){
		flag = data;
	}, function(){
	});
	//return flag.isOrder;
	return flag;
}

function getFormatDate(){
	return new Date().format('yyyy-MM-dd hh:mm:ss');
}

//寄件人保存并收起
function addToSendAddr(){
	
	$("#tab_sendAddr").html('');

    	var fullname = $("#s_fullname");
    	if(fullname.val() == ''){
    		fullname.focus();
    		fullname.blur();
    		return;
    	}
    	var provinceName = $("#s_provinceName");
    	if(provinceName.val() == '' || provinceName.val()==provinceName.attr("tip")){
    		provinceName.focus();
    		return;
    	}
    	var cityName = $("#s_cityName");
    	if(cityName.val() == '' || cityName.val() == cityName.attr("tip")){
    		cityName.focus();
    		return;
    	}
    	var countyName = $("#s_countyName");
    	/*if(countyName.val() == '' || countyName.val() == countyName.attr("tip")){
    		countyName.focus();
    		return;
    	}*/
    	var address = $("#s_address");
    	if(address.val() == '' || address.val() == address.attr("tip")){
    		address.focus();
    		address.blur();
    		return;
    	}
    	var provinceId = $("#s_provinceId").val();
    	var cityId = $("#s_cityId").val();
    	var countyId = $("#s_countyId").val();
    	var company = $("#s_company").val();
    	var phone = $("#s_phone").val();
    	var extnumber = $("#s_extnumber").val();
    	var sqh = $("#s_qh").val();
    	var mobile = $("#s_mobile").val();
    	var weight = $("#weight").val();
    	var remark = $("#remark").val();
    	if(remark == $("#remark").attr("tip")){
    		remark = '';
    	}
    	
    	var sendaddr = '<dl class="address-tips clearfix" id=""><dt class="user">'+
    	'<span id="send_fullname">'+fullname.val() +'</span></dt>'+
    	'<dd class="company"><span id="send_company">'+(company==''?'':company)+'</span></dd>'+
    	'</dl><dl class="address-tips line-t2 clearfix">'+
    	'<dt class="mobilephone"><span id="send_mobile">'+(mobile==''?'':mobile)+
    	'</span></dt><dd class="phone"><span id="send_phone">'+ (sqh==''?'':sqh + '-') + (phone==''?'':phone)+(extnumber==''?'':'-'+extnumber)+
    	'</span></dd><dd class="address-info">'+
    	'<span id="send_provinceName">'+provinceName.val() + '</span>&nbsp;' + 
    	'<span id="send_cityName">'+cityName.val()+'</span>&nbsp;' + 
    	'<span id="send_countyName">'+countyName.val()+'</span>&nbsp;&nbsp;&nbsp;' + 
    	'<span id="send_address">'+address.val() + '</span></dd><dd></dd>'+
    	'<span id="send_provinceId" style="display: none;">'+provinceId+'</span>'+
		'<span id="send_cityId" style="display: none;">'+cityId+'</span>'+
		'<span id="send_countyId" style="display: none;">'+countyId+'</span></dl>'+
		'<p class="pt10"><span class="ml10" id="send_weight">' + i18n.order_weight + weight + 'kg</span>'+
		'<span class="ml10" id="send_remark">' + i18n.order_remark +(remark==''?i18n.order_remark_empty:remark)+ '</span></p>'+
		'<a class="ui-btn btn-normal" style="position:absolute; top:5px; right:10px;_right:40px;" href="javascript:modifySendaddr()"><span class="ui-btn-txt">' + i18n.order_modify + '</span></a>';
    	
    	
    	$("#tab_sendAddr").html(sendaddr).show();
    	$("#sendContextAddr").hide();
	
}


//加载寄件人地址
function loadSendAddr(){
	
	var time = new Date().getTime();
	if(loginStatus == '2'){
		//寄件人地址
		var s_url = window.location.href;
		var sendId = '';
		if(s_url.indexOf("?sendId=") != -1){
			sendId = s_url.substring(s_url.indexOf("?sendId=")+8);
		}
		asyncCallService('/service/addrbook/address/common/send'+'?time='+time+'&sendId='+sendId, 'get', 'JSON', '', function(data){
			if(data != null){
				fillSendDefAddr(data);
			}  
		}, function(){});
	}
}


//加载收件人地址
function loadRecAddr(){
	var time = new Date().getTime();
	if(loginStatus == '2'){
		var r_url = window.location.href;
		var recId = '';
		if(r_url.indexOf("?recId=") != -1){
			recId = r_url.substring(r_url.indexOf("?recId=")+7);
		}
		//收件人地址
		syncCallService('/service/addrbook/address/common/rec'+'?time='+time+"&recId="+recId, 'get', 'JSON', '', function(data){
				addRecContext(data,'init');
		}, function(){
			sfConfirm(i18n.user_timeout, function() {
				login();
			}, function(){
				login();
			});
		});
	}else{
		addRecContext(time,'');
	}
}

$("#newrecmanbtn").click(function(){
	addRecContext(new Date().getTime(),'');
	$("#newrecmanbtn").hide();
});


//修改寄件人地址
function modifySendaddr(){
	$("#tab_sendAddr").hide();
	$("#sendContextAddr").show();
}


//获取提交订单JSON数据
function getFormJson(){
	
	 	var orderType = '';
	 	var print=$('input:radio[name="print"]:checked').val(); 
	 	var nation = $("#nation").val();
		/*if(print=="on" && nation == '中国'){
			orderType = '4';
		}else{
			orderType = '0';
		}*/
	 	if(nation == '中国'){
	 		orderType = print;
	 	}else{
	 		orderType = '0';
	 	}
		var isBooking = '';
		var bookingTm = '';
		var reserveTime = $('input:checkbox[name="reserveTime"]:checked').val();
		if(reserveTime=="on"){
			isBooking = '1';
			var bookingDate = $("#ydate").val();
			var bookingHour = $("#yhour").val();
			var bookingMinute = $("#yminu").val();
			bookingTm = bookingDate + " " + bookingHour + ":" + (bookingMinute==null?"00":bookingMinute + ":00") ;
		}else{
			isBooking = '0';
		}
    	var weight = $("#weight").val();
    	var orderSource = "0";
    	var isSelfSend="0";
    	if("H4"==orderType){
    		orderSource = "HK-0";
    		isSelfSend="1";
    		isBooking = '0';
    		bookingTm = ''
    	}
    	if("ZNZD"==orderType){
    		orderSource = "ZNZD-0";
    		isBooking = '0';
    		bookingTm = ''
    	}
        var orderJson = '"orders":' + 
            '{' +
                '"orderRemark":"' + espaceQuote(($('#remark').val()==$('#remark').attr("tip")?'':$('#remark').val() ))+ '",' +
                '"weight":"' + weight + '",' +
                '"isSelfSend":"' +isSelfSend+ '",' +
                '"orderType":"' + orderType + '",' +
                '"isBooking":"' + isBooking + '",' +
                '"reserveTime":"' + bookingTm + '",' +
                '"orderSource":"' + orderSource + 
            '"}';
        var s_company = $("#send_company").text();
        if(s_company.lastIndexOf(',') != -1){
        	s_company = s_company.substring(0,s_company.lastIndexOf(','));
        }
    	var s_fullname = $("#send_fullname").text();
    	if(s_fullname.lastIndexOf(',') != -1){
    		s_fullname = s_fullname.substring(0,s_fullname.lastIndexOf(','));
        }
    	var s_phone = $("#send_phone").text();
    	if(s_phone.lastIndexOf(',') != -1){
    		s_phone = s_phone.substring(0,s_phone.lastIndexOf(','));
        }
    	var s_mobile = $("#send_mobile").text();
    	if(s_mobile.lastIndexOf(',') != -1){
    		s_mobile = s_mobile.substring(0,s_mobile.lastIndexOf(','));
        }
    	var s_provinceName = $("#send_provinceName").text();
    	var s_cityName = $("#send_cityName").text();
    	var s_countyName = $("#send_countyName").text();
    	var s_address = $("#send_address").text();
    	var s_provinceId = $("#send_provinceId").text();
    	var s_cityId = $("#send_cityId").text();
    	var s_countyId = $("#send_countyId").text();
    	var nation  = $("#nation").val();
        //////////////
    	var obj = $('input:checkbox[name="useRecAddr"]').not("input:checked");
    	if(s_fullname =='' && $("#s_fullname").val()==''){
    		return i18n.order_sender_empty;
    	}
    	var print=$("#print").attr("checked"); 
 		if(print=="checked" && nation == i18n.order_nation_Inland){
 			if(obj.length<=0){
 	    		return i18n.order_recipient_empty;
 	    	}
 		}
    	
    	if(obj.length>=10){
    		return i18n.order_recipient_over_ten;
    	}
        ////////////////
    	var allRec = $("#hideAllRec").is(":visible");
    	//寄件人数据
        var senderJson = '"orderAddress":' + 
            '{' + 
               '"company":"' + espaceQuote(s_company) + '",' +
               '"contactName":"' + espaceQuote(s_fullname) + '",' +
               '"phone":"' + s_phone + '",' +
               '"mobile":"' +s_mobile + '",' +
               '"countryName":"' + espaceQuote(nation) + '",' +
               '"provinceName":"' + espaceQuote(s_provinceName) + '",' +
               '"cityName":"' +espaceQuote(s_cityName) + '",' +
               '"countyName":"' +espaceQuote(s_countyName) + '",' +
               '"provinceId":"' + s_provinceId + '",' +
               '"cityId":"' + s_cityId + '",' +
               '"countyId":"' +s_countyId+ '",' +
               '"address":"' + espaceQuote(s_address) + 
            '"}';
        
        var recErro = "";
    	//收件人数据
        var orderWaybillVOJson = '';
        if(obj.length > 0 && allRec){
                var orderWaybillVOStr = '';
		        orderWaybillVOJson = '"orderWaybillVO":[';
	    	    	
	    	    	$('input:checkbox[name="useRecAddr"]').not("input:checked").each(function(x){
	    	    		var selectRecAddr = $("#selectRecAddr"+$(this).val());
	    	    		
	    	    		var r_goods = selectRecAddr.find("#goodss").text();
		    	    	var r_quantity = selectRecAddr.find("#quantitys").text();
		    	    	//var r_price = selectRecAddr.find("#prices").text();
		    	    	var r_account = selectRecAddr.find("#accounts").text();	    	
		    	    	var r_sendType =selectRecAddr.find('#sendTypes').val();
		    	    	var r_payway = selectRecAddr.find("#hPayWay").val();
//		    	    	if(r_payway == '寄付'){
//		    	    		r_payway = '1';
//		    	    	}else{
//		    	    		r_payway = '2';
//		    	    	}
		    	    	var r_company = selectRecAddr.find("#companys").text();
		    	    	var r_fullname = selectRecAddr.find("#fullnames").text();
		    	    	var r_phone = selectRecAddr.find("#phones").text();
		    	    	var r_mobile = selectRecAddr.find("#mobiles").text();
		    	    	var r_provinceId = selectRecAddr.find("#provinceIds").text();
		    	    	var r_provinceName = selectRecAddr.find("#provinceNames").text();
		    	    	var r_cityId = selectRecAddr.find("#cityIds").text();
		    	    	var r_cityName = selectRecAddr.find("#cityNames").text();
		    	    	var r_countyId = selectRecAddr.find("#countyIds").text();
		    	    	var r_countyName = selectRecAddr.find("#countyNames").text();
		    	    	var r_address = selectRecAddr.find("#addresss").text();
		    	    	
		    	    	
		    	    	var r_prodType = selectRecAddr.find("#prodType").text();
	    	    		
	    	    		//var isSecureValue = r_price !=''?'1':'0';
		    		
		    	    	//获取隐藏域中的附加服务json串
		    	    	var addiSerivcesValue = '';
		    	    	var addiSerivces=$('#addiService').val();
		    	    	if(addiSerivces != undefined && addiSerivces != ''){
		    	    		addiSerivcesValue = addiSerivces+',';
		    	    	}
					   var tempStr = 
				        '{' +
				           '"companyName":"' + espaceQuote(r_company) + '",' +
				           '"contactName":"' + espaceQuote(r_fullname) + '",' +
				           '"phone":"' + r_phone + '",' +
				           '"mobile":"' + r_mobile + '",' +
				           '"countryName":"' + '' + '",' +
				           '"provinceName":"' + espaceQuote(r_provinceName) + '",' +
				           '"cityName":"' + espaceQuote(r_cityName) + '",' +
				           '"countyName":"' + espaceQuote(r_countyName) + '",' +
				           '"provinceId":"' + r_provinceId + '",' +
				           '"cityId":"' + r_cityId + '",' +
				           '"countyId":"' + r_countyId + '",' +
				           '"address":"' + espaceQuote(r_address) + '",' + 
				           '"cargoName":"' + espaceQuote(r_goods) + '",' +
                           '"piece":"' + r_quantity + '",' +
                           //'"secureValue":"' + r_price + '",' + 
                           '"payType":"' + r_payway + '",' +
                           //'"isSecureValue":"' + isSecureValue + '",' +
                           addiSerivcesValue+
                           '"account":"' + r_account + '",' +
                           '"sendType":"' + r_sendType + '",' +
                           '"prodType":"' + r_prodType + 
				        '"},';
					   //alert(tempStr);
					   if("SP334"==r_prodType&&inArray(r_provinceId,noneCrabsProList)){
						   recErro =  i18n.none_crabs_pri_province_batch;
					   }
					   if("SP334"==r_prodType&&"2"==r_payway){
						   recErro = i18n.crabs_none_rec_pay;
					   }
				      orderWaybillVOStr = orderWaybillVOStr + tempStr;
				      
		    	 });
	    	    	setAddressData(orderWaybillVOStr);
		    	 orderWaybillVOJson = orderWaybillVOJson + orderWaybillVOStr.substring(0, orderWaybillVOStr.length-1) + ']';
        }
        ////////设置密码///////
        if(recErro!=""){
        	return recErro;
        }
        var userInfo ='';
	    
	    var formJson;
	    if(typeof(orderWaybillVOJson) == "undefined" || orderWaybillVOJson == ""){
	        if(typeof(userInfo) == "undefined" || userInfo == ""){
	             formJson = "{" + orderJson + "," + senderJson + "}";
	        } else {
	            formJson = "{" + orderJson + "," + senderJson + "," + userInfo + "}";
	        }
	    } else {
	        if(typeof(userInfo) == "undefined" || userInfo == ""){
	           formJson = "{" + orderJson + "," + senderJson + "," + orderWaybillVOJson + "}";
	        } else {
	            formJson = "{" + orderJson + "," + senderJson + "," + orderWaybillVOJson + "," + userInfo + "}";
	        }
	    }
    	return formJson;
       
}
var argsData;
function setSendAddressData(argsData){
	this.argsData =  argsData;
};
function getSendAddressData(){
	return argsData;
};

var argsData;
function setAddressData(argsData){
	this.argsData =  argsData;
};
function getAddressData(){
	return argsData;
};

//从cookie中获取用户名
function getCookie(objName){
    var arrStr = document.cookie.split(";");
    for(var i = 0;i < arrStr.length;i++){
        var temp = arrStr[i].split("=");
        if($.trim(temp[0]) == $.trim(objName)) return temp[1];
   }
   
}

//填充寄件默认地址
function fillSendDefAddr(item){
	$("#s_id").val(item.userAddressId);
	$("#s_company").val(item.company==null?'':item.company);
	$("#s_fullname").val(item.fullname==null?'':item.fullname);
	var phone = item.phone==null?'':item.phone;
	if(phone.indexOf('-', 0) != -1){
		if(phone.split("-").length == 2){
			phone = phone.split('-', 2);
			if(phone[0].length > 4){
				$("#s_phone").val(phone[0]);
				$("#s_extnumber").val(phone[1]);
			} else {
				$("#s_qh").val(phone[0]);
				$("#s_phone").val(phone[1]);
			}
		} else {
			phone = phone.split('-', 3);
			$("#s_qh").val(phone[0]);
			$("#s_phone").val(phone[1]);
			$("#s_extnumber").val(phone[2]);
		}
	}else{
		$("#s_phone").val(phone);
	}
	$("#s_mobile").val(item.mobile==null?'':item.mobile);
	$("#s_countyId").val(item.countyId==null?'':item.countyId);
	$("#s_cityId").val(item.cityId==null?'':item.cityId);
	$("#s_provinceId").val(item.provinceId==null?'':item.provinceId);
	$("#s_countyName").val(item.countyName==null?'':item.countyName);
	$("#s_cityName").val(item.cityName==null?'':item.cityName);
	$("#s_provinceName").val(item.provinceName==null?'':item.provinceName);
	$("#s_address").val(item.address==null?'':item.address);
	var addressFirm = new AddressFirm();
	addressFirm.ChangeFuncName=showZD;
	addressFirm.ChangeAreaFuncName=checkZNZDPrint;
	AddressHelper.loadCityAndAreaData('s_provinceId','s_provinceName','s_cityId','s_cityName','cityBoxBoxId','s_countyId','s_countyName','countyBoxId',addressFirm);
	
	var orderFlag=currentIsOrderEasy();
	var isOrder = orderFlag.isOrder;
	
	if(!isOrder){
		//sfAlert("当前下单时间不是我司服务时间，请预约上门取件时间。 ");
		$("#reserveTime").attr("checked",true);
		$("#yuyue").show();
	}
}

//填充收件默认地址
function fillRecDefAddr(item,id){
	if(item != null && item != undefined){
		$("#r_fullname").val("");
		$("#r_company").val("");
		$("#r_mobile").val("");
		$("#r_phone").val("");
		$("#rextnumber").val("");
		$("#r_qh").val("");
		$("#r_provinceName" + id).val("");
		$("#r_provinceId" + id).val("");
		$("#r_cityName" + id).val("");
		$("#r_cityId" + id).val("");
		$("#r_countyName" + id).val("");
		$("#r_countyId" + id).val("");
		$("#r_address").val("");
		
		var form = $("#recContextAddr"+id);
		$("#r_id").val(item.userAddressId);
		$("#r_company").val(item.company==null?'':item.company);
		$("#r_fullname").val(item.fullname==null?'':item.fullname);
		$("#r_phone").val(item.phone==null?'':item.phone);
		
		
		var phone = item.phone==null?'':item.phone;
		if(phone.indexOf('-', 0) != -1){
			if(phone.split("-").length==2){
				phone = phone.split('-', 2);
				if(phone[0].length > 4){
					$("#r_phone").val(phone[0]);
					$("#rextnumber").val(phone[1]);
				} else {
					$("#r_qh").val(phone[0]);
					$("#r_phone").val(phone[1]);
				}
			} else {
				phone = phone.split('-', 3);
				$("#r_qh").val(phone[0]);
				$("#r_phone").val(phone[1]);
				$("#rextnumber").val(phone[2]);
			}
		}else{
			$("#r_phone").val(phone);
		}
		
		
		$("#r_mobile").val(item.mobile==null?'':item.mobile);
		$("#r_countyId"+id).val(item.countyId==null?'':item.countyId);
		$("#r_cityId"+id).val(item.cityId==null?'':item.cityId);
		$("#r_provinceId"+id).val(item.provinceId==null?'':item.provinceId);
		$("#r_countyName"+id).val(item.countyName==null?'':item.countyName);
		$("#r_cityName"+id).val(item.cityName==null?'':item.cityName);
		$("#r_provinceName"+id).val(item.provinceName==null?'':item.provinceName);
		
		var isUcmp = isUcmpSwitch(); 
		var address = "";
		if(!isUcmp){
			address = item.address;
		}else{
			address = item.address.replace(item.provinceName+item.cityName+item.countyName,'');
		}
		
		$("#r_address").val(address);
		AddressHelper.loadCityAndAreaData('r_provinceId'+id,'r_provinceName'+id,'r_cityId'+id,'r_cityName'+id,'r_cityBoxBoxId'+id,'r_countyId'+id,'r_countyName'+id,'r_countyBoxId'+id);
	}
}

$(function(){	
	loadSendAddr(); //加载寄件人
	loadRecAddr(); //加载收件人
	
	
	
	//初始化不验证密码
	if(loginStatus != '2'){ 
		$("#sendUserAddr").hide();
		$("#recUserAddr").hide();
	}else{
		$("#sendUserAddr").show();
		$("#recUserAddr").show();
	}
	
});

//关闭寄件地址
function closeSendAddr(){
	$("#sendContextAddr").hide();
	$("#tabs_sendAddr").hide();
}

//修改寄件地址信息
function modifySendAddr(id){
	$("#tab_sendAddr").hide();
	$("#sendContextAddr").show();
	asyncCallService('/service/addrbook/address/'+id, 'get', 'JSON', '', function(data){
		fillSendDefAddr(data);
	}, function(){});
}


function changePrint(obj){
	
	if($("#heike:checked").length>0){
		$("#heike_prompt").html("<span class=\"hot\" style=\"color:blue\">注：当前可支持城市为"+initHeikePrompt()+"</span>");
	}else{
		$("#heike_prompt").html("<span class=\"hot\" style=\"color:blue\">&nbsp;</span>");
	}
	
	var print=obj.value; 
	if(print != '0'){
		if($("#nation").val()==i18n.order_nation_Inland){
			$("#hideAllRec").show();
			$("#addrecdiv").show();
		}
	}else{
		$("#hideAllRec").hide();
		$("#addrecdiv").hide();
	}
	if("H4"==print||"ZNZD"==print){//嘿客门店自寄,隐藏预约
		$("#reserveTime:checked").attr("checked",false);
		$("#reserveTime:visible").parent().parent().hide().next("#yuyue:visible").hide();
	}else{
		$("#reserveTime:hidden").parent().parent().show().find(":checked").parent().parent().next("#yuyue:hidden").show();
	}
	//判断是否是子权限，是否选中终端打印，
	var result="0";
	/**
	 * 加载该用户是否开启子用户优惠件
	 */
	if(getL()=='2'){
		syncCallService("/service/subaccount/getIsPreferentialByParent", "get", "json", "", 
				function(data){
					result=data;
				}, function(data) {
					sfAlert("系统繁忙!!!!");
				});
	}
	
	var custType = getCT();
	$("#payway option[value='4']").remove();
	$("#account").val('').hide();
	$("#accountLabel").val('').hide();
	/*$('.selectout1').hide();//代码回退
	if((custType!='2'&&custType!='1')||result!='1' || print =='10'){
		$("#payway option[value='4']").remove();
		$("#payway").render();
	}else{
		$("#payway").append("<option value='4' >"+i18n.order_payment_prepaid_month+"</option>").render();
	}
	*/
	$('.selectout1').parent().hide();
	//if(!(print !='10'&&result!='1')&&getL()!='0'){
	if(getL()!='0'){
			$("#payway").append("<option value='4' >"+i18n.order_payment_prepaid_month+"</option>").render();
	}
	$("#payway").render();
	
	
	
}
	
/*$("#print").click(function(){
	
});*/
$("#china").click(function(){
	$("#abroad").removeClass();
	$(this).addClass("ie6png selected");
	$("#nation").val("中国");
	$("#printDiv").show();
	$("#heike_div").show();
	var print=$("#4print").attr("checked"); 
	var print10 = $("#10print").attr("checked");
	if($("#heike:checked").length>0){
		$("#heike_prompt").html("<span class=\"hot\" style=\"color:blue\">注：当前可支持城市为"+initHeikePrompt()+"</span>");//北京、上海、广州、深圳、东莞
	}else{
		$("#heike_prompt").html("<span class=\"hot\" style=\"color:blue\">&nbsp;</span>");
	}
	if(print=='checked' || print10 == 'checked'){
		$("#hideAllRec").show();
		$("#addrecdiv").show();
	}else{
		$("#hideAllRec").hide();
		$("#addrecdiv").hide();
	}
	$("#prompt").hide();
});

$("#abroad").click(function(){
	$("#china").removeClass();
	$(this).addClass("ie6png selected");
	$("#nation").val("港澳台");
	$("#printDiv").hide();
	$("#heike_div").hide();
	$("#heike_prompt").html("<span class=\"hot\" style=\"color:blue\">&nbsp;</span>");
	//$("#s_address").val("");
	$("#hideAllRec").hide();
	$("#addrecdiv").hide();
	$("#prompt").show();
	$("#stopTime").empty().hide();	
});

function initHeikePrompt(){
	var heikePromptStr="北京、上海、广州、深圳、东莞";
	syncCallService("/service/order/getHeikeArea", "get", "json", "", function(data){
		heikePromptStr=data;
	}, function(){});
	return heikePromptStr;
}

$("#order_mobileValidate").click(function(){
	$("#order_login").removeClass();
	$(this).addClass("ie6png selected");
	$("#mobileValidateBody").show();
	$("#loginBody").hide();
});

$("#order_login").click(function(){
	$("#order_mobileValidate").removeClass();
	$(this).addClass("ie6png selected");
	$("#mobileValidateBody").hide();
	$("#loginBody").show();
});


$("#reserveTime").click(function(){
    var reserveTime = $('input:checkbox[name="reserveTime"]:checked').val();
    if(reserveTime == undefined){
    	$("#yuyue").hide();
    }else{
    	$("#yuyue").show();
    }
});






//新增收件人地址信息
function addRecMsg(index) {
	var id = "'" + index + "'";
	
	var rows = '<div class="address-list line-t2" style="display:none;" id="selectRecAddr'
			+ index
			+ '">'
			+'<input type="checkBox" style="display: none" id="useRecAddr" name="useRecAddr" value="'+index+'">'
			+ '<div class="p10 clearfix"><span class="fl">'
			+ '<span class="mr5" id="fullnames" name="fullnames"></span>'
			+ '<span class="mr5" id="companys" name="companys"></span>'
			+ '<span class="mr5" id="mobiles" name="mobiles"></span>'
			+ '<span class="mr5" id="phones" name="phones"></span>'
			+ '<span class="mr5" id="provinceNames" name="provinceNames"></span>'
			+ '<span class="mr5" id="cityNames" name="cityNames"></span>'
			+ '<span class="mr5" id="countyNames" name="countyNames"></span>'
			+ '<span class="mr5" style="display:none;" id="provinceIds" name="provinceIds"></span>'
			+ '<span class="mr5" style="display:none;" id="cityIds" name="cityIds"></span>'
			+ '<span class="mr5" style="display:none;" id="countyIds" name="countyIds"></span>'
			+ '<span class="mr5" style="display:none;" id="prodType" name="prodType"></span>'
			+ '<span class="mr5" id="addresss"></span>'
			+ '<span class="mr5" style="display:none;" id="accounts"></span>'
			+ '</span><span class="fr"><a class="ui-btn btn-normal" href="javascript:modifyRecaddr('+ id+ ')"><span class="ui-btn-txt">'
			+ i18n.order_modify
			+ '</span></a>&nbsp;<!--<a class="ui-btn btn-normal" href="javascript:removeSelectRecAddr('
			+ id + ')"><span class="ui-btn-txt">' + i18n.order_delete
			+ '</span></a>--></span></div><dl class="address-tips clearfix">'
			+ '<dt>' +
			// 单反相机
			'<span id="goodss"></span> × <span id="quantitys"></span>'
			+ '</dt>'
			+'<dd class="line" id="dd_prices">'
	   		+ i18n.order_insure+'<span id="prices"></span>'+ i18n.order_yuan
	        +'</dd>'
			+ '<dd class="line">'
			// 付款方式
			+'<input type="hidden" id="hPayWay" value=""/>'
			+'<input type="hidden" id="sendTypes" value=""/>'
			+'<span id="selectPay"></span></dd></dl></div> ';
	return rows;
}

//修改收件人
function modifyRecaddr(index){
	$("#recContextAddr" + index).show();
	$("#selectRecAddr" + index).hide();
}

//删除已选收件人地址
function removeSelectRecAddr(id){
	sfConfirm(i18n.order_confirm_delete,function(){
		if(loginStatus == '2'){
	        asyncCallService('/service/addrbook/address/'+id, 'delete', 'JSON', '', function(data){
	            $("#selectRecAddr"+id).remove();
	        }, function(){});
		}
		$("#recContextAddr" + id).remove();
	 	$("#selectRecAddr" + id).remove();
	 },function(){});
   
}
//取消
function cancelRecContext(index){
	var form = $("#recContextAddr"+index);
	var id = form.find("#r_id").val();
	if(id !='' && id.length==32){
		sfConfirm(i18n.order_confirm_cancel,function(){
			$("#selectRecAddr" + index).remove();
			$("#recContextAddr" + index).remove();
		},function(){});
	}else{
		$("#selectRecAddr" + index).remove();
		$("#recContextAddr" + index).remove();
	}
}

//编辑收件人
function addRecContext(item,type) {
	var company = '';
	var fullname = '';
	var mobile = '';
	var phone = '';
	var extnumber = '';
	var rqh = '';
	var provinceId = '';
	var provinceName = '';
	var cityId = '';
	var cityName = '';
	var countyId = '';
	var countyName = '';
	var address = '';

	
	var recUserAddrHideStyle = "display:none";
	if(loginStatus == '2'){
		recUserAddrHideStyle = '';
	}
	
	
	var index = '';
	if (loginStatus == '2' && type == 'init' && item != null && item != '' && item != undefined) {
		index = item.userAddressId == null ? '' : item.userAddressId;
		company = item.company == null ? '' : item.company;
		fullname = item.fullname == null ? '' : item.fullname;
		mobile = item.mobile == null ? '' : item.mobile;

		var p_obj = item.phone == null ? '' : item.phone;
		if (p_obj.indexOf('-', 0) != -1) {
			if(p_obj.split("-").length == 2){
				p = p_obj.split('-', 2);
				if(p[0].length > 4){
					phone = p[0];
					extnumber = p[1];
				} else {
					rqh = p[0];
					phone = p[1];
				}
			} else {
				p = p_obj.split('-', 3);
				rqh = p[0];
				phone = p[1];
				extnumber = p[2];
			}
		} else {
			phone = p_obj;
		}

		provinceId = item.provinceId == null ? '' : item.provinceId;
		provinceName = item.provinceName == null ? '' : item.provinceName;
		cityId = item.cityId == null ? '' : item.cityId;
		cityName = item.cityName == null ? '' : item.cityName;
		countyId = item.countyId == null ? '' : item.countyId;
		countyName = item.countyName == null ? '' : item.countyName;
		address = item.address == null ? '' : item.address;
	} else {
		provinceName = i18n.order_province;
		cityName = i18n.order_city;
		countyName = i18n.order_district;
		address = i18n.myorder_detail_address_1;
		index = item;
	}
	var id = "'" + index + "'";
	var addressStr = '<script>';
	addressStr += 'var r_aBox ="r_countyBoxId' + index + '";';
	addressStr += 'var r_cBox ="r_cityBoxBoxId' + index + '";';
	addressStr += 'var r_pBox ="r_provinceBoxId' + index + '";';
	addressStr += 'var r_aId = "r_countyId' + index + '";';
	addressStr += 'var r_cId = "r_cityId' + index + '";';
	addressStr += 'var r_pId = "r_provinceId' + index + '";';
	addressStr += 'var r_aName = "r_countyName' + index + '";';
	addressStr += 'var r_cName = "r_cityName' + index + '";';
	addressStr += 'var r_pName = "r_provinceName' + index + '";';
	addressStr += 'var addressFirm = new AddressFirm();addressFirm.provinceChangeFunc = '+provinceChangeFunc+';';
	addressStr += 'initAddress(r_pBox,r_pName,r_pId,r_cBox,r_cName,r_cId,r_aBox,r_aName,r_aId,addressFirm);';
	addressStr += '</script>';

	//var expressProductType = getAddiService('CN','EXPRESS_PRODUCT');
	var expressProductType = getAddiService('CN','ORDER_EXPRESS_PRODUCT');
	
	var payType = getAddiService('CN','PAY_TYPE');
	var rows = addressStr
			+ '<div class="pt10 line-t2" id="recContextAddr'+ index+ '">'
			+ '<form id="recForm'+ index+ '" method="post">  '
			+ ' <table width="100%" class="table-order">'
			+ '<colgroup>'
			+ '<col width="10%" /><col width="40%" /> <col width="35%" /><col width="" />'
			+ '</colgroup>'
			+ '<tbody>      '
			
			+ '<tr>'
			+ '<td colspan="4"><span id="rec_Validform_checktip" class="Validform_checktip"></span></td>'
			+ '</tr>'
			
			+ '<tr>'
			+ '<th><label>'+ i18n.order_name+ '</label></th>'
			+ '<td>'
			+'<input type="text" class="input-text input-short" id="r_fullname" name="rfullname"  value="'+ fullname+'" size="25" maxlength="10"/>'
			+'<input type="text" style="display:none;" id="r_id" name="rid"  value="'+ index+'" size="25" />'
			+ '<span class="hot ml5">*</span><span id="fullname_valid" class="Validform_checktip"></span></td>'
			+ '<td><div id="rcompanyvisible2'+ index
			+ '">'+ '<label class="mr5">'
			+ i18n.order_recipient_company+ '</label>'
			+ '<input type="text" class="input-text input-short" id="r_company" name="rcompany"  value="'+ company
			+ '" size="25" maxlength="30"/><span class="Validform_checktip"></span>'+ '</div></td>'
			+ '<td class="tr"><div id="recUserAddr" style="'+recUserAddrHideStyle+'"><a class="ml5" id="torecaddr" onclick="getRecAddr('+id+')"><b class="ui-icon icon-addressbook"></b>'+i18n.order_recipient_address_book_select+'</a></div></td>'
			+ '</tr>'+ '<tr>'+ '<th><label>'+ i18n.order_phone+ '</label></th>'
			+ '<td><input type="phone" class="input-text input-short" id="r_mobile" onblur="verifyMobile('+id+')" name="rmobile" value="'+ mobile
			+ '" size="20" /><span id="mobile_valid" class="Validform_checktip">'+ i18n.order_phone_or_telephone+ '</span></td>'
			+ '<td colspan="2"><label class="mr5">'+ i18n.order_telephone
			+ '</label><input type="text" id="r_qh" name="rqh" class="input-text input-mishort" value="' + rqh + '" maxlength="4" size="5" onblur="verifyQh('+id+')"/> - '
			+ '<input type="phone" id="r_phone" name="rphone" maxlength="8" onblur="verifyPhone('+id+')" class="input-text input-short" value="'+ phone
			+ '" size="20" /> - <input type="text" class="input-text input-mishort" maxlength="5" id="rextnumber" onblur="verifyExtNumber('+id+')" name="rextnumber" value="'+ extnumber
			+ '" size="5" /><span id="phone_valid" class="Validform_checktip">'
			+ i18n.order_telephone_style+ '</span></td>'
			+ '</tr> '+ '<tr>'+ '<th><label>'+ i18n.order_address+ '</label></th>'+ '<td colspan="3">'
			+ '<input type="hidden" id="r_provinceId'+ index+ '" name="rprovinceId'+ index+ '"  value="'+ provinceId+ '"/> '
			+ '<input type="hidden" id="r_cityId'
			+ index+ '" name="rcityId'+ index+ '" value="'+ cityId+ '"/> '
			+ '<input type="hidden" id="r_countyId'+ index+ '" name="rcountyId'+ index+ '" value="'+ countyId+ '" /> '
			+ '<input class="input-text input-address tipsgray" id="r_provinceName'
			+ index+ '" type="text"  name="rprovinceName" altercss="tipsgray" size="20" value="'+ provinceName+ '" tip="'
			+ i18n.order_province+ '" /> '
			+ '<input class="input-text input-address tipsgray" id="r_cityName'+ index
			+ '" type="text"  name="rcityName" altercss="tipsgray" size="20" value="'+ cityName
			+ '" tip="'+ i18n.order_city+ '" /> '
			+ '<input class="input-text input-address tipsgray" id="r_countyName'+ index
			+ '" type="text"  name="rcountyName" altercss="tipsgray" size="20" value="'+ countyName+ '" tip="'
			+ i18n.order_district+ '" /> '
			+ '<input id="r_address" name="raddress" type="text"  class="input-text input-addr tipsgray" value="'+ address
			+ '" tip="'+i18n.myorder_detail_address_1+'"  size="46" maxlength="40" onblur="checkRecVirtualAddress('+id+')" onFocus="clearInputTextTips();"/><span class="hot ml5">*</span><span id="address_valid'+ index+'" class="Validform_checktip"></span>'
			+ '</td>'+ '</tr>    '+ '</tbody>'+ '</table>'
			+ '<table width="100%" class="table-order">'
			+ '<colgroup><col width="10%" /><col width="35%" /><col width="8%" /><col width="14%" /><col width="8%" /> <col width="" />'
			+ '</colgroup>'+ '<tbody>'
			+ ' <tr>'
			+ ' <th><label>'+ i18n.order_cargo+ '</label></td>'
			
			
			+ '<td><input type="text" class="input-text input-maxshort" id="goods" errormsg="'+ i18n.order_add_shipments
			+ '" nullmsg="'+ i18n.order_add_shipments
			+ '" name="goods" size="25" value="" maxlength="33"/><span class="hot ml5">*</span><span id="goods_valid" class="Validform_checktip"></span></td>'
			+ '<th><label>'+ i18n.order_amount+ '</label></th>'
			
			
			+ ' <td colspan="0"><input type="text" class="input-text input-short" onblur="verifyQuantity('+id+')" id="quantity" errormsg="'
			+ i18n.order_shipments_amount+ '" nullmsg="'+ i18n.order_shipments_amount
			+ '" name="quantity" size="25" maxlength="5" value="" /><span class="hot ml5">*</span><span id="quantity_valid" class="Validform_checktip"></span></p> '
			+ '</td>'
			+'</tr>'
		//快递产品	
			+ ' <tr>'
			+ '<th><label>'+i18n.order_shipment_type+'：</label></th> '
			+ '<td><div class="selectout"><select selwidth="90" id="prodType" name="prodType" size="1" onchange="changeProdType();">'
			+expressProductType
			/*+'<option value="T4">'+i18n.order_standard_express+'</option>'   //标准件
			+'<option value="T5">'+i18n.order_common_express+'</option>'   //普货件
			+'<option value="T6">'+i18n.order_privilege_express+'</option>'  //特惠件
*/			//+'<option value="T8">'+i18n.order_safety_express+'</option>'     //特安件
			+'</select></div>'
			+ '</td> '
		//付款方式
			+ '<th><label>'
			+ i18n.order_payment+ '</label></th>'
			+ ' <td><div class="selectout"><select onchange="changeAccount('+id+')" selwidth="80" id="payway" name="payway" size="1">'
			+payType
			+'</select></div></td>'+ ' <td style="display:none;"><div class="selectout1"><select  selwidth="80" id="sendType" name="sendType" size="1"><option value="1">公司件</option>'//代码回退
			+'<option value="2">个人件</option>'
			+'</select></div></td>'+' <th><label id="accountLabel" style="display:none;">'
			+ i18n.order_account+ '</label></th>'
			+ ' <td><input type="text" id="account" class="input-text input-short input-disable" ignore="ignore"  style="display:none;" errormsg="'
			+ i18n.order_account_empty+ '" nullmsg="'+ i18n.order_account_empty
			+ '" name="account" value="" size="15" maxlength="15" disabled="disabled"/><span id="account_valid" class="Validform_checktip"></span></td>'
			+ '</tr>'+ '</tbody>  '+ '</table>  '
			
		/*	+'<table width="100%" class="table-order">'
			+'<tr>'
			+'<td>'
			+'<div>'
			+'<p>温馨提示：保价费用</p>'
			+'<p>１. 快件的声明价值不得超过快件实际价值，最高声明价值不超过20,000元 。</p>'
			+'<p>２. 若您的单票快件声明价值超过20,000元，请您选择我司<a href="javascript:open('http://www.sf-express.com/cn/sc/product_service/product_intro/express_delivery.html')" class="unl hot">顺丰特安</a>。</p>'
			+'</div>'
			+'</td>'
			+'</tr>'
			+'</table>'*/
			//附加服务链接
			+'<p class="pt10 pl30"><a class="unl hot" onclick="goAdditionService();">'+i18n.additional_service+'</a></p>'
			
			+ '<div class="tc pt20 pb10"><a class="ui-btn btn-submits" but="sub" onclick="saveRec('
			+ id
			+ ')" ><span class="ui-btn-txt fb">'+ i18n.order_save
			+ '</span></a></div>' + '</form>'
			+ '<script type="text/javascript" src="/resources/js/select.js"></script>'
			+ '</div>';
	
	renderProdTypeForOrder(provinceId);
	$("#recs").append(addRecMsg(index)).append(rows);
	$("#payway").render();
	//删除电商件
	/*$("#prodType option[value='C801']").remove();
	$("#prodType option[value='T7']").remove();
	$("#prodType").render();*/
	var objDiv = $("#recs").find("div:eq(2)");
	if(objDiv.hasClass("line-t2")){
		objDiv.removeClass("line-t2");
	}
	var result="0";
	/**
	 * 加载该用户是否开启子用户优惠件
	 */
	if(getL()=='2'){
		syncCallService("/service/subaccount/getIsPreferentialByParent", "get", "json", "", 
				function(data){
					result=data;
				}, function(data) {
					sfAlert("系统繁忙!!!!");
				});
	}
	var printval = $('input:radio[name="print"]:checked').val();
	var custType = getCT();
	/*if((custType!='2'&&custType!='1')||result!='1' || printval =='10'){//代码回退
		$("#payway option[value='4']").remove();
	}*/
	//三合一支持月结
	if(getAreaCode() !='CN'){//只支持大陆月结
		if(printval !='10'&&result!='1'){
			$("#payway option[value='4']").remove();
		}
	}else{
		if(getL()!='2'){
			$("#payway option[value='4']").remove();
		}
	}
	
}

function clearInputTextTips() {
	var value = $("#r_address").val();
	if(value == $("#r_address").attr("tip")) {
		$("#r_address").val("");
	}
}

var provinceChangeFunc = function(id){
	//非大闸蟹专递省份需隐藏大闸蟹选项
	if($("select[name='prodType']").val()!="SP334"){
		renderProdTypeForOrder(id);	
	}
};
function changeAccount(index){
	
	var div = $("#recContextAddr"+ index);
	var payway = div.find("#payway");
	/*//代码回退
	if(payway.val() == '2' || payway.val() == '1'){
		div.find("#account").val('').hide();
		div.find("#accountLabel").val('').hide();
		$('.selectout1').hide();
	}else{
		div.find("#account").show();
		div.find("#accountLabel").show();
		$('.selectout1').show();
		loadUserAccountNoForRec();
	}
	*/
	div.find("#account").val('').hide();
	div.find("#accountLabel").val('').hide();
	$('.selectout1').parent().hide();
	$("#account").removeAttr("disabled").removeClass("input-disable");
	var printval = $('input:radio[name="print"]:checked').val();
	if(payway.val() == '4'){
		div.find("#account").show();
		div.find("#accountLabel").show();
		if(printval!='10'){
			if(getCT() == '1'){  //非月结用户屏蔽
				$('.selectout1').parent().show();
			}
			if(getAreaCode() !='CN'){//只支持大陆月结
				$("#account").attr("disabled","disabled").addClass("input-disable");
			}
			loadUserAccountNoForRec();
		}
	}
}

//保存收件地址
var security_payway_value = 50000;
function saveRec(index) {
	
	var form = $("#recForm" + index);
	var fullname = form.find("input[@type=text][name=rfullname]");
	var company = form.find("input[@type=text][name=rcompany]");
	var mobile = form.find("input[@type=text][name=rmobile]");
	var phone = form.find("input[@type=text][name=rphone]");
	var rextnumber = form.find("input[@type=text][name=rextnumber]");
	var rqh = form.find("input[@type=text][name=rqh]");
	var provinceId = form.find("input[@type=text][name=rprovinceId" + index+ "]");
	var cityId = form.find("input[@type=text][name=rcityId" + index + "]");
	var countyId = form.find("input[@type=text][name=rcountyId" + index + "]");
	var cityName = form.find("input[@type=text][name=rcityName]");
	var provinceName = form.find("input[@type=text][name=rprovinceName]");
	var countyName = form.find("input[@type=text][name=rcountyName]");
	var address = form.find("input[@type=text][name=raddress]");
	var goods = form.find("input[@type=text][name=goods]");
	var quantity = form.find("input[@type=text][name=quantity]");
	var price = form.find("input[@type=text][name=price]");
	var account = form.find("input[@type=text][name=account]");
	var sendType = form.find("select[name=sendType]");
	var prodType = form.find("select[name=prodType]");
	
	
	var payway = form.find("select[name=payway]");
	var cb =  form.find('input:checkbox[name="cb_price2"]:checked');
	
	if(!verifyRec(index)){ //表单验证
		return;
	}
	if(!checkRecVirtualAddress(index)){
		$("#rec_Validform_checktip").text(i18n.order_address_accept_all).addClass("Validform_wrong");
		return false;
	};
	/*if(prodType.val() == 'T8'){
		var insureTxt = $("#insureTxt").val();
		if(insureTxt > security_payway_value && payway.val() == '2'){
			$("#rec_Validform_checktip").text(i18n.security_payway_value).addClass("Validform_wrong");
			return;
		}else{
			$("#rec_Validform_checktip").text('').removeClass("Validform_wrong");
		}
		
		var insureChx =  $('input:checkbox[name="insureChx"]:checked').val();
		var insureTxt = $("#insureTxt").val();
		if(insureChx == undefined || insureTxt == ''){
			$("#rec_Validform_checktip").text(i18n.security_value).addClass("Validform_wrong");
			return;
		}else{
			$("#rec_Validform_checktip").text('').removeClass("Validform_wrong");
		}
	}*/
	
	var r_phone = phone.val();
	var r_extnumber = rextnumber.val();
	var r_qh = rqh.val();
	
	var option = '';
	if("1" == payway.val()){
		option = i18n.order_payment_prepaid;
	}else if("2" == payway.val()){
		option = i18n.order_payment_freight_collect;
	}else if("3" == payway.val()){
		option = i18n.order_payment_third_party;
	}else if("4" == payway.val()){
		option = i18n.order_payment_prepaid_month;
	}
	
	var userAddrId = form.find("input[@type=text][name=rid]").val();
	if (loginStatus == '2') {
		var params = {
				'rid' : userAddrId.length < 32 ? '' : userAddrId,
						'rcompany' : company.val(),
						'rfullname' : fullname.val(),
						'rphone' : (r_phone==''?'':r_phone)+(r_extnumber==''?'':'-'+r_extnumber),
						'rmobile' : mobile.val(),
						'rprovinceId' : provinceId.val(),
						'rprovinceName' : provinceName.val(),
						'rcityId' : cityId.val(),
						'rcityName' : cityName.val(),
						'rcountyId' : countyId.val(),
						'rcountyName' : countyName.val(),
						'raddress' : address.val(),
						'raddressType' : 'R',
						'rqh':r_qh	
		};
		syncCallService('/service/addrbook/address/save/orderaddr',"post","json",params,function(data) {
			
			form.find("input[@type=text][name=rid]").val(data);
		
		}, function() {
		});
			
	}
	
	$("#recContextAddr" + index).hide();
	$("#selectRecAddr" + index).show();
	
	var selectRecAddr = $("#selectRecAddr" + index);
	selectRecAddr.find("#fullnames").text(fullname.val());
	selectRecAddr.find("#companys").text(company.val());
	selectRecAddr.find("#mobiles").text(mobile.val());
	selectRecAddr.find("#phones").text((r_qh==''?'':r_qh + '-') + (r_phone==''?'':r_phone)+(r_extnumber==''?'':'-'+r_extnumber));
	selectRecAddr.find("#provinceNames").text(provinceName.val());
	selectRecAddr.find("#cityNames").text(cityName.val());
	selectRecAddr.find("#countyNames").text(countyName.val());
	selectRecAddr.find("#addresss").text(address.val());
	selectRecAddr.find("#goodss").text(goods.val());
	selectRecAddr.find("#quantitys").text(quantity.val());
	
	selectRecAddr.find("#provinceIds").text(provinceId.val());
	selectRecAddr.find("#cityIds").text(cityId.val());
	selectRecAddr.find("#countyIds").text(countyId.val());
	selectRecAddr.find("#accounts").text(account.val());
	selectRecAddr.find("#sendTypes").val(sendType.val());
	
	selectRecAddr.find("#prodType").text(prodType.val());
	
	if(price.val() != '' && cb.val() == "on"){
		selectRecAddr.find("#dd_prices").show();
		selectRecAddr.find("#prices").text(price.val());
	}else{
		selectRecAddr.find("#dd_prices").hide();
		selectRecAddr.find("#prices").text('');
	}
	selectRecAddr.find("#selectPay").text(option);
	selectRecAddr.find("#hPayWay").val(payway.val());//隐藏的付款方式
	
	
	var objDiv = $("#recs").find("div:eq(0)");
	if(objDiv.hasClass("line-t2")){
		objDiv.removeClass("line-t2");
	}
	
}

/*$(function(){
	setInterval("showZD()",1000);
});

function showZD(){
	var countyId = $("#s_countyId").val();
	var val = $('input:radio[name="print"]:checked').val(); 
	if(countyId == i18n.order_area_nanshan || countyId == i18n.order_area_futian ){
		$("#doReceive").show();
		$("#noprint_lable").hide();
		if(val != 10 && val != 4){
			$('#4print').attr("checked",true);
		}
	}else{
		
		if(val == 10){
			$('#4print').attr("checked",true);
		}
		$("#doReceive").hide();
		$("#noprint_lable").show();
	}
}*/

//三合一打印机
var showZD = function(cityId){
	//港澳台下单不作处理
	if($("#abroad").hasClass("selected")) return;
	
	if(!AddressHelper.isEmpty(cityId)){
		var val = $('input:radio[name="print"]:checked').val();
		syncCallService('/service/order/isZDArea'+'?time='+new Date().getTime()+'&cityId='+cityId, 'post', 'JSON', '', function(data){
			if(data.THREEONEPRO == true){
				if(data.THREEONECOUPON == true){
					$("#doReceive").show();
					$("#doReceiveCoupon").show();
					$("#noprint_lable").hide();
					if(val != 10 && val != 4){
						$('#4print').attr("checked",true);
					}
				}else{
					$("#doReceive").show();
					$("#noprint_lable").hide();
					$("#doReceiveCoupon").hide();
					if(val != 10 && val != 4){
						$('#4print').attr("checked",true);
					}
				}
				$("#hideAllRec").show();
				$("#addrecdiv").show();
			}else{
				if(val == 10){
					$('#4print').attr("checked",true);
				}
				$("#doReceive").hide();
				$("#noprint_lable").show();
				$("#doReceiveCoupon").hide();
			}
			if(!$("#heike:checked").length>0){
				$("#reserveTime:hidden").parent().parent().show().find(":checked").parent().parent().next("#yuyue:hidden").show();
			}
		}, function(){
			if(val == 10){
				$('#4print').attr("checked",true);
			}
			$("#doReceive").hide();
			$("#noprint_lable").show();
			$("#doReceiveCoupon").hide();
			if(!$("#heike:checked").length>0){
				$("#reserveTime:hidden").parent().parent().show().find(":checked").parent().parent().next("#yuyue:hidden").show();
			}
		});
		
		
		
		
		asyncCallService('/service/order/order/reserveTime/'+cityId, 'get', 'JSON', '', function(data){
			var cityName = $("#s_cityName").val();
			$("#stopTime").html(' '+cityName + i18n.order_stop_time + data+' ').show();
		}, function(){
			
		});
		//清楚预约时间
		$("#ydate").val('');
		$("#yhour").val('');
		$("#yminu").val('');
	}else{
		$("#stopTime").empty().hide();
	}
};



//计算保价费用
function countPrice(index){
	var form = $("#recForm"+index);
	var cb = form.find('input:checkbox[name="cb_price2"]:checked');
	if(cb.val() == undefined){
		sfAlert(i18n.order_insure_without_price);
		return;
	}
	var price = form.find("input[@type=text][name=price]").val();
	if(price =='' || price == undefined || price == i18n.order_declared_price){
		sfAlert(i18n.order_insure_without_price);
		return;
	}
	var goods = form.find("input[@type=text][name=goods]").val();
	if(goods == '' || goods == undefined){
		sfAlert(i18n.order_add_shipments);
		return;
	}
	var p = parseInt(price);
	
	if(i18n.order_file_shipments.indexOf(goods)!=-1){
		if(p>=2000){
			sfAlert(i18n.order_file_shipments_over_declared_price);
			return;
		}
	}else{
		if(p>=20000){
			sfAlert(i18n.order_shipments_over_declared_price);
			return;
		}
	}
	var sf = '';
	if(p > 1000){
		sf = p * 5 / 1000;
	}else if(p >= 501 && p <=1000){
		sf = '2';
	}else if(p>=1 && p<=500){
		sf = '1';
	}
	price_dialog = art.dialog({
  	title : i18n.order_insure_price,
  	background : 'none',
  	padding : 0,
  	width:'300px',
  	content :  '<div class="p10" style="text-align:left;"><p><b>' + i18n.order_shipments + '</b>'+goods+ '</p><p class="pt5"><b>' + i18n.order_declared_price + '</b>'+p + i18n.order_yuan +
      '</p><p class="pt5"><b>' + i18n.order_insure_price + '</b>'+Math.round(sf) + i18n.order_yuan + '</p>' +
              '<div class="pt10"><p><b>' + i18n.order_reminding + '</b></p>' +
'<p class="pt5">1. ' + i18n.order_reminding_msg_first + '</p> ' +
'<p class="pt5">2. ' + i18n.order_reminding_msg_second + '</p>' +
'<p class="pt5">3. ' + i18n.order_reminding_msg_third + '</p></div></div>'
  	
  });
}

function price_checkbox(index) {
	var form = $("#recForm" + index);
	var cb = form.find('input:checkbox[name="cb_price2"]:checked');
	if (cb.val() == undefined) {
		form.find("input[@type=text][name=price]").attr("ignore", "ignore");
		$("#price2_div" + index).hide();
	} else {
		form.find("input[@type=text][name=price]").removeAttr("ignore");
		$("#price2_div" + index).show();
	}
}

//打开附加服务模态框
var addiServiWindow='';
function goAdditionService(){
	addiServiWindow=art.dialog({
		title : i18n.additional_service,
		padding:10,                                            
		lock:true,                                             
		content : document.getElementById('addiServiceDiv')
	});
	$('#excepMsg').html('').removeClass("Validform_wrong");
	var addiSevices=$('#addiService').val();
	if(''!=addiSevices && null!=addiSevices){
		addiSevices=eval('({'+addiSevices+'})');
		if(addiSevices.isSecureValue=='1'){
			$('#insureChx').attr('checked',true);
			$('#insureTxt').val(addiSevices.secureValue);
		}
		if(addiSevices.isOtherFee=='1'){
			$('#otherFeeChx').attr('checked',true);
			$('#otherFee').val(addiSevices.otherFee);
		}
		
		if(addiSevices.isSelfPickUp=='1'){
			$('#selfPickUpChx').attr('checked',true);
		}
		
		if(addiSevices.isSignBack=='1'){
			$('#signBackChx').attr('checked',true);
		}
		
		//alert(addiSevices.isSecureValue);
	}
	//暂时注释,
	//initWindow();
}

//企业用户才能签回单和设置其它费用
function initWindow(){
	$.ajax({
		url : '/service/user/getUserTypeInfo',
		type : 'get',
		data : '',
		contentType: "application/x-www-form-urlencoded; charset=utf-8", 
		dataType : 'JSON',
		success : function(item) {
			  if('1'==item){
				 $('#speciUserTr').show(); 
			  }else{
				  $('#speciUserTr').hide(); 
			  }
		}
	});
	
}

//关闭附加服务窗口
function closeAddiServWindow(){
	if(addiServiWindow!='' || addiServiWindow!=null || addiServiWindow!=undefined){
		addiServiWindow.close();
	}
}
//保存附加服务数据
function saveAddiServData(){
	//保价
	var isSecureValue='0';
	var secureValue='';
	if($('#insureChx').attr('checked')=='checked'){
		isSecureValue='1';
		if(validateInsure()==true){
			secureValue=$('#insureTxt').val();
		}else{
			return;
		}
	}
	
	//其它费用
	var otherFeeVal='';
	var isOtherFee='0';
	if($('#otherFeeChx').attr('checked')=='checked'){
		isOtherFee='1';
		if(validateOtherFee()==true){
			otherFeeVal=$('#otherFee').val();
		}else{
			return;
		}
	}
	//自取
	var selfPickUpVal='0';
	if($('#selfPickUpChx').attr('checked')=='checked'){
		selfPickUpVal='1';
	}
	//签回单
	var signBackVal='0';
	if($('#signBackChx').attr('checked')=='checked'){
		signBackVal='1';
	}
	var addiSerices='"isSecureValue":"'+isSecureValue+'","secureValue":"'+secureValue
	+'","isOtherFee":"'+isOtherFee+'","otherFee":"'+otherFeeVal
	+'","isSelfPickUp":"'+selfPickUpVal+'","isSignBack":"'+signBackVal+'"';
	//保存到隐藏域，提交订单时提交
	$('#addiService').val(addiSerices);
	closeAddiServWindow();
	//alert(addiSerices);
}
function otherFeeClick(){
	//勾选其它费用复选框
		if($('#otherFeeChx').attr('checked')=='checked'){
			$('#otherFeeDiv').show();
		}else{
			$('#otherFee').val('');
			$('#otherFeeDiv').hide();
		}
}

//验证其它费用
function validateOtherFee(){
	var val=$('#otherFee').val();
	var re0=/^[1-9]$/;
	var re1=/^[1-9][\d]$/;
	if($.trim(val)==''){
		$('#excepMsg').html('<font class=Validform_wrong>' + i18n.order_other_expenses + '</font');
		return false;
	}
	if(!re0.test(val) && !re1.test(val)){
		$('#excepMsg').html('<font class=Validform_wrong>' + i18n.order_numbers_range + '</font');
		return false;
	}
	return true;
}

//保价是否复选
function insureClick(){
	if($('#insureChx').attr("checked")=='checked'){
		$('#insureDiv').show();
	}else{
		$('#insureDiv').hide();
		$("#insureTxt").val('');
	}
}


var securityOrder_month_value = 300000;
var securityOrder_value = 200000;
var commonOrder_value = 20000;
//校验保价费，必须是正整型数字
function validateInsure(){
			var msgBox=$('#excepMsg');
			var price = $('#insureTxt');
			if($('#insureChx').attr("checked")=='checked'){
				if (price.val() == '') {
					msgBox.html(i18n.order_declared_price_empty).addClass(
							"Validform_wrong");
					return false;
				} else if (price.val() != '') {
					var reg =/^[1-9]{1}[\d]*$/;
					var reg2 = /^0\.?0+$/;
					var reg3 = /^\d+$/;
					if (price.val() == '0' || reg2.test(price.val())) {
						msgBox.html(i18n.order_declared_price_zero).addClass(
								"Validform_wrong");
						return false;
					}
					if (!reg.test(price.val()) || !reg3.test(price.val())) {
						msgBox.html(i18n.order_declared_price_wrong).addClass(
								"Validform_wrong");
						return false;
					}
					if(price.val()>1000000){
						msgBox.html(i18n.order_declared_price_tooMax).addClass(
						"Validform_wrong");
						return false;
					}
					
					//var payway = $("select[name=payway]");
					//var prodType = $("select[name=prodType]");
					/*if(prodType.val() == 'T8'){//特安件
						if(payway.val() == 4 || payway.val() == 3){  //月结客户
							if(price.val() > securityOrder_month_value){
								msgBox.html(i18n.order_declared_price_tooMax_by_month).addClass(
									"Validform_wrong");
								return false;
							} 
						}else{
							if(price.val() > securityOrder_value){
								msgBox.html(i18n.order_declared_price_tooMax_by_other).addClass(
									"Validform_wrong");
								return false;
							
							} 
						}
					}else{
						if(price.val() > commonOrder_value){
							msgBox.html(i18n.order_declared_price_tooMax).addClass(
								"Validform_wrong");
							return false;
						
						} 
					}*/
					msgBox.html("").removeClass("Validform_wrong");
				}else {
					msgBox.html("").removeClass("Validform_wrong");
				}
			}
			return true;
}

var selProType='T4';
function changeProdType(){
	var prodTypeVal = $("select[name='prodType']").val();
	selProType=prodTypeVal;//$('#prodType').val();
	if("SP334" == prodTypeVal){//如果过是大闸蟹，隐藏到付
		$("#payway option").detach("[value='2']").parent().render();
	}else{
		if($("#payway option[value='2']").length==0){
			$("#payway").append('<option value="2">到付</option>').render();
		}
	}
}
//表格行鼠标移上去高亮
function trMouseover(id){
	$(id).addClass("hover");
	}
function trMouseout(id){
	$(id).removeClass("hover");	
	}
//表格行点击变色
function trOnClick(id){
	if ($(id).hasClass("selected")) {
	$(id).removeClass("selected").find(":radio").attr("checked",false);
	}else{
	$(id).siblings("tr").removeClass("selected").end().addClass("selected").find(":radio").attr("checked",true);
	}
	}

	
function objToJsonStr(obj) {
	var isFirstEle = true;
	var result = "{";
	for ( var i in obj) {
		if (isFirstEle) {
			isFirstEle = false;
		} else {
			result += ",";
		}
		var val = (null == obj[i] || "null" == obj[i]) ? "" : obj[i];
		result += "'" + i + "':'" + val + "'";
	}
	result += "}";
	return result;
}
function loadUserAccountNoForRec(){
	if($('#account').val()==null 
			|| $('#account').val()==''){
		asyncCallService("/service/batchOrder/user/cardno", "get", "json", "", function(data){
			$('#account').val(data);
		}, function(){});
	}
}

//var none
var checkZNZDPrint = function (){
	var provinceId = $("#s_provinceId").val();
	var cityId = $("#s_cityId").val();;
	var districtId = $("#s_countyId").val();;
	var address = $("#s_address").val();;
	var orderType = "0";
	if(provinceId==""||cityId==""||districtId=="")return;
	var znzdPrintSurport = checkSenderAddSurportZnzd(provinceId,cityId,districtId,address,orderType);
	if("1"==znzdPrintSurport){
		//显示智能终端打印，隐藏预约
		//显示智能终端打印，隐藏预约
		$("#znzd_lable").show();
		//$("#reserveTime").attr("checked",false).parent().parent().hide().next("#yuyue:visible").hide().find("input").val("");
	}else{
		$("#znzd_lable").hide();
		$("#4print").attr("checked","check");
		$("#reserveTime:hidden").parent().parent().show().find(":checked").parent().parent().next("#yuyue:hidden").show();
	}
};

firsSeccSend('');
function firsSeccSend(val){
	if('cn'==getRegionCode()){
		if(val=='1'){//点击进来的
			$(".tabs-content .tabs-box.minheight").css("padding-top", "20px");
			$("#firsSeccSend").css("display", "none");
			return;
		}
		if('0'==getL() || ('2'==getL() && '0'==getUT() && '0'==isCustMem())){//未登录的 或 （已登录且 非内部员工非企业用户的普通会员）
			syncCallService('/service/user/getSendFullGive/mem_first_succe_send', 'get', 'json', '', function(data) {
				var temp = '<div style="float:left;">会员专享寄件优惠，';
				var firstRule = false, sendFullGiveRule=false;
				if(data.mem_coupon_amt_fir!=undefined){
					temp += '首寄电子运单立返'+data.mem_coupon_amt_fir+'元券，';
					firstRule =true;
				}
				if(data.send_count!=undefined){
					if(firstRule){
						temp += '累计满'+data.send_count+'票再享赠券！';
					}else{
						temp += '累计满'+data.send_count+'票享赠'+data.mem_coupon_count+'张'+data.mem_coupon_amt+'元顺丰券的优惠，多寄多得！';
					}
					sendFullGiveRule =true;
				}
				if(!firstRule && !sendFullGiveRule){
					firsSeccSend(1);
					return;
				}
				if(getL()=='0'){
					temp += '还不是会员，<a style="color:blue;" onclick="register()"><u>立即注册</u></a>';
				}

				if(isEndWith(temp, '，')){
					temp = temp.substring(0, temp.length-'，'.length);
				}
				if(firstRule && !sendFullGiveRule){
					temp = temp.replace('首寄电子运单立返'+data.mem_coupon_amt_fir+'元券',
					'首次使用自助工具成功寄件即享立返'+data.mem_coupon_count_fir+'张'+data.mem_coupon_amt_fir+'元顺丰券的优惠');
				}
				temp +='</div>';
				temp += '<div style="padding-right:7px;float:right;">';
				temp += '<a onclick="firsSeccSend(1)"><img src="../../../resources/images/close.png"/></a>';
				temp += '</div>';
				$("#firsSeccSend").html(temp);
				$("#firsSeccSend").css("display", "");
				$(".tabs-content .tabs-box.minheight").css("padding-top", "0px");
			});
		}
	}
}

//注册
function register() {
	var gotoUrl = getUrlPara("url");
	regUrl = "/"+i18n.name +"/user/register/"  + "register.html";
	if (gotoUrl != null || gotoUrl != "" || gotoUrl != undefined){
		regUrl += "?url="+gotoUrl;
	}
	window.location.href = regUrl;
}

function isEndWith(val, str){
	if(val.lastIndexOf(str) == val.length-str.length){
		return true;
	}
	return false;
}


function sendBookQueryLike(){
	$("#send_address_info").find("#pageNo").val(1);
	var condition = $("#sendlike").val();
	var tipValue = $("#sendlike").attr("tip");
	if(condition==tipValue){
		condition = '';
	}
	getSenderAddr(encodeURIComponent(condition));
}
function recBookQueryLike(){
	$("#rec_address_info").find("#pageNo").val(1);
	var condition = $("#reclike").val();
	var tipValue = $("#reclike").attr("tip");
	if(condition==tipValue){
		condition = '';
	}
	getRecAddr("",encodeURIComponent(condition));
}

$("#sendlike").focus(function(){
	if($("#sendlike").val() == $("#sendlike").attr("tip")){
		$("#sendlike").val("");
	}
});

$("#sendlike").focusout(function(){
	if($("#sendlike").val() == ''){
		$("#sendlike").val($("#sendlike").attr("tip"));
	}
});

$("#reclike").focus(function(){
	if($("#reclike").val() == $("#reclike").attr("tip")){
		$("#reclike").val("");
	}
});

$("#reclike").focusout(function(){
	if($("#reclike").val() == ''){
		$("#reclike").val($("#reclike").attr("tip"));
	}
});

